import React, { useRef } from 'react'
import { Modal, Space, Button, message } from 'antd'
import PropTypes from 'prop-types'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { CaseContext } from '../../../context'
import { updatePartyRequest, deletePartyRequest } from '../ajax/partyAjax'
import { awaitWrap } from '@js/tool'
import { normalStatusList } from '@js/config'
import ModalForm from './ModalForm'
const { confirm } = Modal
// 获取默认值
function getInitialValues (caseid, type, initialValues) {
  if (!initialValues) {
    initialValues = {}
  }
  return {
    caseid,
    type,
    ...initialValues
  }
}

// 表单回调，提交数据
async function onFinish (data, caseid, type, list, callback, hide) {
  data.caseid = caseid
  data.type = type
  if (data.subject_type === '自然人') {
    data.legal = ''
  }
  const h = message.loading('提交中', 120)
  const [e, d] = await awaitWrap(updatePartyRequest(data))
  h()
  if (e) {
    return message.warning(e.message)
  }
  const ids = list.map(li => li.id)
  const index = ids.indexOf(d.id)
  const l = list ? [...list] : []
  l.splice(index, 1, d)
  callback(l)
  hide()
}

// 删除当事人回调
function deletePartyHandle (data, status, caseFormRef, type, list, callback, hide) {
  if (!validateAgent(data, caseFormRef, type)) {
    return false
  }
  confirm({
    title: '提示',
    icon: <ExclamationCircleOutlined />,
    content: '您确定要撤销该当事人吗？',
    onOk: () => {
      if (normalStatusList.indexOf(status) === -1) {
        reallyDeleteParty(data, list, callback, hide)
      } else {
        setPartyDisable(data, list, callback, hide)
      }
    },
    onCancel () {},
    okText: '确定',
    cancelText: '取消'
  })
}

// 真实删除当事人
async function reallyDeleteParty (data, list, callback, hide) {
  const h = message.loading('撤销中', 120)
  const [e] = await awaitWrap(deletePartyRequest(data.id))
  h()
  if (e) {
    return message.warning(e.message)
  }
  const ids = list.map(li => li.id)
  const index = ids.indexOf(data.id)
  const l = list ? [...list] : []
  l.splice(index, 1)
  callback(l)
  hide()
}

// 设置当事人为无效
async function setPartyDisable (data, list, callback, hide) {
  const h = message.loading('撤销中', 120)
  const [e, d] = await awaitWrap(updatePartyRequest({ ...data, status: 0 }))
  h()
  if (e) {
    return message.warning(e.message)
  }
  const ids = list.map(li => li.id)
  const index = ids.indexOf(data.id)
  const l = list ? [...list] : []
  l.splice(index, 1, d)
  callback(l)
  hide()
}

// 获取代理人列表
function getAgentList (formRef, type) {
  const c = formRef.current
  if (!c) {
    return []
  }
  const keyMap = {
    申请人: 'applicant',
    被申请人: 'respondents'
  }
  const key = keyMap[type] + '_agents'
  const m = c.getFieldValue([key])
  return m
}

// 验证当事人是否有代理人
function validateAgent (data, caseFormRef, type) {
  const agentList = getAgentList(caseFormRef, type)
  const agentNames = []
  agentList.forEach(agent => {
    const ids = agent.party.map(li => li.partyid)
    if (ids.indexOf(data.id) !== -1) {
      agentNames.push(agent.name)
    }
  })
  // 校验当事人是否绑定了代理人，如果绑定了，则不允许删除当事人
  if (agentNames.length) {
    Modal.warning({
      title: '提示',
      content: `${data.name} 已委托了代理人（${agentNames.join('、')}），请先解除代理关系后再删除${type} ${data.name}。`,
      okText: '确定'
    })
    return false
  }
  return true
}

// 确定是否恢复
function recoveryConfirm (data, list, callback, hide) {
  confirm({
    title: '提示',
    icon: <ExclamationCircleOutlined />,
    content: `您确定要将 ${data.name} 重新加入案件吗？`,
    onOk: async () => {
      const h = message.loading('恢复中', 120)
      const [e, d] = await awaitWrap(updatePartyRequest({ ...data, status: 1 }))
      h()
      if (e) {
        return message.warning(e.message)
      }
      const ids = list.map(li => li.id)
      const index = ids.indexOf(data.id)
      const l = list ? [...list] : []
      l.splice(index, 1, d)
      callback(l)
      hide()
    },
    onCancel () {},
    okText: '确定',
    cancelText: '取消'
  })
}

// 渲染模态框按钮
function Footer ({ formRef, hide, initialValues, type, caseFormRef, value, onChange }) {
  return (
    <CaseContext.Consumer>
      {({ id, dictionaries, isPre, status }) => {
        if (initialValues.status === 0) {
          return (
            <Space>
              <Button onClick={hide}>取消</Button>
              <Button type='primary' ghost onClick={() => recoveryConfirm(initialValues, value, onChange, hide)}>恢复</Button>
            </Space>
          )
        }
        return (
          <Space>
            <Button ghost danger onClick={() => deletePartyHandle(initialValues, status, caseFormRef, type, value, onChange, hide)}>撤销</Button>
            <Button onClick={hide}>取消</Button>
            <Button type='primary' onClick={() => formRef.current.submit()}>确定</Button>
          </Space>
        )
      }}
    </CaseContext.Consumer>
  )
}

Footer.propTypes = {
  formRef: PropTypes.object,
  hide: PropTypes.func,
  initialValues: PropTypes.object,
  type: PropTypes.string,
  caseFormRef: PropTypes.object,
  value: PropTypes.array,
  onChange: PropTypes.func
}

Footer.defaultProps = {
  formRef: null,
  hide: () => {},
  initialValues: {},
  type: '',
  caseFormRef: null,
  value: [],
  onChange: () => {}
}

function Main ({ visible, type, hide, initialValues, value, onChange, caseFormRef }) {
  const formRef = useRef(null)
  return (
    <Modal
      width='700px'
      title={`修改${type}`}
      open={visible}
      onCancel={hide}
      maskClosable={false}
      footer={<Footer formRef={formRef} hide={hide} initialValues={initialValues} type={type} caseFormRef={caseFormRef} value={value} onChange={onChange} />}
      destroyOnClose
    >
      <CaseContext.Consumer>
        {({ id, dictionaries, isPre }) => (
          <ModalForm ref={formRef} isPre={isPre} initialValues={getInitialValues(id, type, initialValues)} dictionaries={dictionaries} onFinish={d => onFinish(d, id, type, value, onChange, hide)} />
        )}
      </CaseContext.Consumer>
    </Modal>
  )
}

Main.propTypes = {
  visible: PropTypes.bool,
  type: PropTypes.string,
  hide: PropTypes.func,
  initialValues: PropTypes.object,
  value: PropTypes.array,
  onChange: PropTypes.func,
  caseFormRef: PropTypes.object
}

Main.defaultProps = {
  visible: false,
  type: '',
  hide: () => {},
  initialValues: null,
  value: [],
  onChange: () => {},
  caseFormRef: null
}

export default Main
